﻿var customerID = "";
var customersCommandName = "";
var ordersCommandName = "";
var customersTableView = null;
var ordersTableView = null;

function RadGrid1_Command(sender, args) {
	args.set_cancel(true);

	WebService.GetCustomers(customersTableView.get_currentPageIndex() * customersTableView.get_pageSize(),
                    customersTableView.get_pageSize(),
                        customersTableView.get_sortExpressions().toString(), customersTableView.get_filterExpressions().toDynamicLinq(),
                            updateGrid);
	customersCommandName = args.get_commandName();
}

function RadGrid1_RowSelected(sender, args) {
	customerID = args.get_gridDataItem().get_cell("CustomerID").innerHTML;
	loadOrders();
}

function updateGrid(result) {
	customersTableView.set_dataSource(result);
	customersTableView.dataBind();

	if (result.length > 0) {
		customersTableView.selectItem(0);
		customerID = result[0]["CustomerID"];
	}
	else {
		customerID = "";
	}


	if (customersCommandName == "Filter" || customersCommandName == "Load") {
		WebService.GetCustomersCount(updateVirtualItemCount);
	}

	loadOrders();
}

function loadOrders() {
	ordersCommandName = "Load";

	WebService.GetOrdersByCustomerID(customerID, ordersTableView.get_currentPageIndex() * ordersTableView.get_pageSize(),
            ordersTableView.get_pageSize(),
                    ordersTableView.get_sortExpressions().toString(), ordersTableView.get_filterExpressions().toDynamicLinq(),
                        updateOrdersGrid);
}

function updateVirtualItemCount(result) {
	customersTableView.set_virtualItemCount(result);
}


function RadGrid2_Command(sender, args) {
	args.set_cancel(true);

	ordersCommandName = args.get_commandName();

	WebService.GetOrdersByCustomerID(customerID, ordersTableView.get_currentPageIndex() * ordersTableView.get_pageSize(),
                ordersTableView.get_pageSize(),
                    ordersTableView.get_sortExpressions().toString(), ordersTableView.get_filterExpressions().toDynamicLinq(),
                        updateOrdersGrid);
}

function updateOrdersGrid(result) {
	ordersTableView.set_dataSource(result);
	ordersTableView.dataBind();

	if (ordersCommandName == "Filter" || ordersCommandName == "Load") {
		WebService.GetOrdersByCustomerIDCount(updateOrdersVirtualItemCount);
	}
}

function updateOrdersVirtualItemCount(result) {
	ordersTableView.set_virtualItemCount(result);
}